package com.wang.interview.N02_Singleton;

import org.springframework.context.annotation.Lazy;

import java.util.concurrent.*;

/**
 * @author: wang
 * @date: 2021/7/12 20:31
 * @description:懒汉
 * 饿汉直接使用静态属性，私有化构造。或者使用枚举。或者使用静态代码块，方便加载配置文件
 *
 */
public class Lazy01 {
    private static Pojo pojo;
    private Lazy01(){}

    public static Pojo getPojo() throws InterruptedException {  // 线程安全
        if ( pojo == null ){
            Thread.sleep(100);
            synchronized(Lazy.class){
                if ( pojo == null ){
                    pojo = new Pojo();
                }
            }
        }
        return pojo;
    }
}
class TestLazy{
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 回顾线程池和callable
        Callable<Pojo> c = new Callable<Pojo>() {
            @Override
            public Pojo call() throws Exception {
                return Lazy01.getPojo();
            }
        };

        ExecutorService es =  Executors.newFixedThreadPool(2);
        Future<Pojo> s1 = es.submit(c);
        Future<Pojo> s2 = es.submit(c);
        Pojo p1 = s1.get();
        Pojo p2 = s2.get();
        System.out.println( p1 == p2 );
        es.shutdown();

    }
}